﻿#include "linechart.h"
#include <QDebug>

LineChart::LineChart(QWidget* parent)
	: QWidget(parent)
{
	x_max = 100.0;
	y_max = 100.0;
	point_radius = 5;
	link_count = 0.0;
	link_animation = new QPropertyAnimation(this);
	link_animation->setTargetObject(this);
	link_animation->setDuration(800);
	connect(link_animation, &QPropertyAnimation::valueChanged, this, [=](const QVariant& value)
		{
			link_count = value.toDouble();
			update();
		});
}

void LineChart::addData(CPoint value, const QColor& color, const QString& desc)
{
	//按照x大小顺序插入
	for (int i = 0; i < chart_value.size(); i++)
	{
		if (chart_value[i].x > value.x)
		{
			chart_value.insert(i ,value);
			chart_color.insert(i, color);
			chart_desc.insert(i, desc);
			return;
		}
	}
	chart_value.push_back(value);
	chart_color.push_back(color);
	chart_desc.push_back(desc);
}

void LineChart::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);
	int start_x = (width() - chart_width) / 2;
	int start_y = (height() - chart_height) / 2;
	//绘制坐标轴
	painter.drawLine(QPoint(start_x, start_y + chart_height), QPoint(start_x, start_y));
	painter.drawLine(QPoint(start_x, start_y + chart_height), QPoint(start_x + chart_width, start_y + chart_height));
	painter.drawLine(QPoint(start_x, start_y), QPoint(start_x - 6, start_y + 8));
	painter.drawLine(QPoint(start_x, start_y), QPoint(start_x + 6, start_y + 8));
	painter.drawLine(QPoint(start_x + chart_width, start_y + chart_height), QPoint(start_x + chart_width - 8, start_y + chart_height + 6));
	painter.drawLine(QPoint(start_x + chart_width, start_y + chart_height), QPoint(start_x + chart_width - 8, start_y + chart_height - 6));
	//按照x大小逐个绘制
	for (int i = 0; i < chart_value.size(); i++)
	{
		if ((int)link_count < i)
			break;
		double rate = link_count;
		while (rate > 1)
			rate -= 1;
		QPoint center(start_x + chart_width * chart_value[i].x / x_max, start_y + chart_height * (1 - chart_value[i].y / y_max));
		if (i != chart_value.size() - 1)
		{
			QPoint next_center(start_x + chart_width * chart_value[i + 1].x / x_max, start_y + chart_height * (1 - chart_value[i + 1].y / y_max));
			int dx = (next_center.x() - center.x()) * rate;
			int dy = (next_center.y() - center.y()) * rate;
			painter.setPen(QPen(chart_color[i], 3));
			if ((int)link_count == i)
				painter.drawLine(center, QPoint(center.x() + dx, center.y() + dy));
			else
				painter.drawLine(center, next_center);
		}
		painter.setPen(QPen());
		painter.setBrush(QBrush(chart_color[i]));
		painter.drawEllipse(center.x() - point_radius, center.y() - point_radius, point_radius * 2, point_radius * 2);
	}
}

void LineChart::resizeEvent(QResizeEvent* event)
{
	chart_width = width() * 0.8;
	chart_height = height() * 0.8;
}

void LineChart::mousePressEvent(QMouseEvent* event)
{
	link_animation->setStartValue(0.0);
	link_animation->setEndValue((double)chart_value.size());
	link_animation->setDuration(chart_value.size() * 250);
	link_animation->start();
}
